package com.example.mypplication.expendlist

import android.content.Context
import android.content.res.Resources
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.mypplication.R

class FlexboxExpandAdapter(
    private val context:Context,
    private val items: List<String>,
    private val buttonWidth: Int,
    private val horizontalSpacing: Int,
    private var recyclerViewWidth: Int
) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    // 缓存item宽度和行数
    private val itemInfoCache = mutableMapOf<Int, ItemInfo>()

    data class ItemInfo(
        var width: Int,
        val line: Int
    )

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        super.onAttachedToRecyclerView(recyclerView)
            calculateItemsLayout()
    }

    private fun calculateItemsLayout() {
        if (recyclerViewWidth == 0) return

        var currentLine = 1
        var currentLineWidth = 0

        items.forEachIndexed { index, item ->
            val itemWidth = measureItemWidth(item)
            val currentWidth = currentLineWidth + itemWidth + horizontalSpacing

            // 检查是否需要换行
            if (currentWidth > recyclerViewWidth) {
                currentLine++
                currentLineWidth = itemWidth
            } else {
                currentLineWidth += itemWidth + horizontalSpacing
            }
            Log.d("FlexboxExpandAdapter", "currentWidth=$currentWidth recyclerViewWidth=$recyclerViewWidth currentLine=$currentLine $item")
            itemInfoCache[index] = ItemInfo(itemWidth, currentLine)
        }
    }

    private fun measureItemWidth(text: String): Int {
        val textView = TextView(context).apply {
            setText(text)
            setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            setPadding(8.dpToPx(), 8.dpToPx(), 8.dpToPx(), 8.dpToPx())
        }

        textView.measure(
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        )

        return textView.measuredWidth
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_flexbox, parent, false)
        return ItemViewHolder(view)
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is ItemViewHolder) {
            val itemInfo = itemInfoCache[position]
            itemInfo?.let{
                holder.bind(items[position], it)
            }
        }
    }

    override fun getItemCount(): Int = items.size

    inner class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val textView: TextView = view.findViewById(R.id.textView)
//        private val lineIndicator: TextView = view.findViewById(R.id.lineIndicator)

        fun bind(text: String, itemInfo: ItemInfo) {
            textView.text = "$text"
            textView.width = itemInfo.width

            // 设置item宽度
//            val layoutParams = itemView.layoutParams
//            if (layoutParams is FlexboxLayoutManager.LayoutParams) {
//                layoutParams.width = width
//                itemView.layoutParams = layoutParams
//            }

            // 显示所在行数
//            lineIndicator.text = "Line $line"
        }
    }
}

// 扩展函数：dp转px
fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()